<?php

namespace addons\sum\library;

use addons\sum\exception\Exception;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use think\Log;

use GuzzleHttp\Exception\RequestException;

class PaynowService
{
    protected $serviceURL;
    protected $WebNo;
    protected $Password;
    protected $ECPlatform;
    protected $rand;
    protected $isTest = 1;
    public $method;

    public function __construct()
    {
        $paymentConfig = json_decode(\addons\sum\model\Config::get(['name' => 'paynow'])->value, true);
        $this->isTest=$paymentConfig['is_test'];
        $this->WebNo = ucfirst($paymentConfig['web_no']);														//賣家登入帳號，如身分證開頭請為大寫傳送。
        $this->Password = $paymentConfig['password'];
        $this->ECPlatform = $paymentConfig['ec_platform'];
        if($this->isTest){
            //測試
            $this->serviceURL = "https://test.paynow.com.tw/service/etopm.aspx";
        }else{
            $this->serviceURL = "https://www.paynow.com.tw/service/etopm.aspx";
        }



    }
    public function create($order,$params)
    {
        //        $order = [
        //            'out_trade_no' => time(),
        //            'total_fee' => '1', // **单位：分**
        //            'body' => 'test body - 测试',
        //            'openid' => 'onkVf1FjWS5SBIixxxxxxx', //微信需要带openid过来
        //        ];
        $data["WebNo"] = $this->WebNo;
        $data["ECPlatform"] = $this->ECPlatform;
        $data["ReceiverName"] = $order["last_name"].$order["first_name"];								//消費者姓名
        $data["ReceiverID"] = $order["email"];								//消費者身分證/Email/手機號碼
        $data["ReceiverTel"] = $order["phone"];								//消費者姓名
        $data["ReceiverEmail"] = $order["email"];							//消費者Email
        $data["OrderNo"] = $params["out_trade_no"]; 								//訂單編號
        $data["TotalPrice"] = (int)$order["total_fee"];						//交易金額 台湾的金额不能有小数点？
        $data["OrderInfo"] = $this->ECPlatform;												//商家自訂交易訊息
        $data["PayType"] = $params['method']??"01";															//01 : 信用卡
        //02 : WebATM
        //03 : 虛擬帳號
        //05 : 代碼繳費
        //09 : 銀聯
        //10 : 超商條碼
        //11 : 分期付款
        $data["PayEN"] = $params['pay_en']??"0";
        //將以下的順序組合起來成一字串 :( WebNo & OrderNo & Total Price& 商家交易密碼) 並使用 SHA-1 雜湊函數取得組合字串的雜湊值
        $data["PassCode"] = strtoupper(sha1($data["WebNo"].$data["OrderNo"].$data["TotalPrice"].$this->Password)); 	//交易驗證碼

        //※ 所有參數傳遞時，請以URL Encode 編碼，所有網頁字集為UTF-8
        $data = array_map("urlencode", $data);
        $pay=$this->buildPayHtml($this->serviceURL,$data);
        return $pay;
    }

    /**
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    function checkPassCode($data){
        return ($data["PassCode"] == strtoupper(sha1($data["WebNo"].$data["OrderNo"].$data["TotalPrice"].$this->Password)));
    }

    /**
     * Build Html response.
     *
     * @author yansongda <me@yansongda.cn>
     *
     * @param string $endpoint
     * @param array  $payload
     * @param string $method
     */
    protected function buildPayHtml($endpoint, $payload, $method = 'POST'): Response
    {
        if ('GET' === strtoupper($method)) {
            return new RedirectResponse($endpoint.'&'.http_build_query($payload));
        }

        $sHtml = "<form id='paynow_submit' name='paynow_submit' action='".$endpoint."' method='".$method."'>";
        foreach ($payload as $key => $val) {
            $val = str_replace("'", '&apos;', $val);
            $sHtml .= "<input type='hidden' name='".$key."' value='".$val."'/>";
        }
        $sHtml .= "<input type='submit' value='ok' style='display:none;'></form>";
        $sHtml .= "<script>document.forms['paynow_submit'].submit();</script>";

        return new Response($sHtml);
    }
}
